package com.atguigu.gmall.item.service.impl;

import com.atguigu.gmall.common.bean.ResponseVo;
import com.atguigu.gmall.item.feign.PmsClient;
import com.atguigu.gmall.item.feign.SmsClient;
import com.atguigu.gmall.item.feign.WmsClient;
//import com.atguigu.gmall.item.service.IndexService;
import com.atguigu.gmall.item.service.ItemService;
import com.atguigu.gmall.item.vo.ItemVo;
import com.atguigu.gmall.pms.entity.*;
import com.atguigu.gmall.pms.vo.ItemGroupVo;
import com.atguigu.gmall.pms.vo.ItemSkuAttrsVo;
import com.atguigu.gmall.sms.vo.ItemSaleVo;
import com.atguigu.gmall.wms.entity.WareSkuEntity;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
import java.util.stream.Collectors;

@Service
public class ItemServiceImpl implements ItemService {
    @Autowired
    PmsClient pmsClient;
    @Autowired
    WmsClient wmsClient;
    @Autowired
    SmsClient smsClient;
    @Autowired
    ThreadPoolExecutor executor;
    @Override
    public ItemVo queryItemVo(String skuId) {
        System.out.println("查询商品："+skuId+"的详情业务被访问了.....");
        //将上面的所有的数据解析出来设置给ItemVo对象
        ItemVo itemVo = new ItemVo();
        //需要远程访问 pms  sms wms
//        查询数据模型需要的数据：接口会接收到skuId
//        1、根据skuid查询sku数据：pms_sku
        CompletableFuture<SkuEntity> c1 = CompletableFuture.supplyAsync(() -> {
            ResponseVo<SkuEntity> skuEntityResponseVo = pmsClient.querySkuById(Long.parseLong(skuId));
            SkuEntity skuEntity = skuEntityResponseVo.getData();
            if (skuEntity == null) {
                return null;
            }
            itemVo.setWeight(Double.parseDouble(skuEntity.getWeight().toString()));
            itemVo.setTitle(skuEntity.getTitle());
            itemVo.setPrice(skuEntity.getPrice());
            itemVo.setSkuId(skuEntity.getId().toString());
            itemVo.setSubtitle(skuEntity.getSubtitle());
            itemVo.setDefaultImage(StringUtils.isEmpty(skuEntity.getDefaultImage()) ? "https://ggmall.oss-cn-shanghai.aliyuncs.com/2020-03-21/a3a0a224-caad-4af2-8eec-f62c0e49a51f_e9ad9735fc3f0686.jpg" :
                    skuEntity.getDefaultImage());
            itemVo.setSpuId(skuEntity.getSpuId().toString());
            return skuEntity;
        }, executor);


//        categoryId/brandId/spuId
//        2、根据skuId得到的category3Id查询123级分类集合，并按照123的顺序存储：pms_category
        //依赖于1的结果
        CompletableFuture<Void> c2 = c1.thenAcceptAsync((skuEntity) -> {
            Long category3Id = skuEntity.getCategoryId();
            ResponseVo<List<CategoryEntity>> queryLevel123CatesResponseVo = pmsClient.queryLevel123Cates(category3Id.toString());
            List<CategoryEntity> categories = queryLevel123CatesResponseVo.getData();
            if (!CollectionUtils.isEmpty(categories)) {
                itemVo.setCategories(categories);
            }
        }, executor);


//        3、根据skuId得到的brandId查询品牌：pms_brand
        //依赖于1的结果
        CompletableFuture<Void> c3 = c1.thenAcceptAsync((skuEntity) -> {
            Long brandId = skuEntity.getBrandId();
            ResponseVo<BrandEntity> brandEntityResponseVo = pmsClient.queryBrandById(brandId);
            BrandEntity brand = brandEntityResponseVo.getData();
            if (brand != null) {
                itemVo.setBrandId(brand.getId().toString());
                itemVo.setBrandName(brand.getName());
            }
        }, executor);

//        4、根据skuId查询是否有货： wms_ware_sku
        //和1并行
        CompletableFuture<Void> c4 = CompletableFuture.runAsync(() -> {
            ResponseVo<List<WareSkuEntity>> wareSkuResponseVo = wmsClient.queryWareSkusBySkuId(skuId);
            List<WareSkuEntity> wareSkuEntities = wareSkuResponseVo.getData();
            if (!CollectionUtils.isEmpty(wareSkuEntities)) {
                itemVo.setStore(wareSkuEntities.stream()
                        .anyMatch(wareSkuEntity -> wareSkuEntity.getStock() - wareSkuEntity.getStockLocked() > 0));

            }
        }, executor);

//        5、根据skuId查询图片列表和默认图片： pms_sku_images
        //和1并行
        CompletableFuture<Void> c5 = CompletableFuture.runAsync(() -> {
            ResponseVo<List<SkuImagesEntity>> skuImagesResponseVo = pmsClient.querySkuImagesBySkuId(skuId);
            List<SkuImagesEntity> skuImagesEntities = skuImagesResponseVo.getData();
            if (!CollectionUtils.isEmpty(skuImagesEntities)) {
                itemVo.setImages(skuImagesEntities);
            }
        }, executor);

//        6、根据skuId查询营销信息： sms_sku_xxx
        //和1并行
        CompletableFuture<Void> c6 = CompletableFuture.runAsync(() -> {
            //[{type:'满减' , desc:"满1000减100"}]
            ResponseVo<List<ItemSaleVo>> itemSalevosResponseVo = smsClient.querySalesBySkuId(skuId);
            List<ItemSaleVo> itemSaleVos = itemSalevosResponseVo.getData();
            if (!CollectionUtils.isEmpty(itemSaleVos)) {
                itemVo.setSales(itemSaleVos);
            }
        }, executor);


//        7、根据spuId查询spu数据：pms_spu
        //依赖于1的结果
        CompletableFuture<Void> c7 = c1.thenAcceptAsync((skuEntity) -> {
            Long spuId = skuEntity.getSpuId();
            ResponseVo<SpuEntity> spuEntityResponseVo = pmsClient.querySpuById(spuId);
            SpuEntity spuEntity = spuEntityResponseVo.getData();
            if (spuEntity != null) {
                itemVo.setSpuName(spuEntity.getName());
            }
        }, executor);

//        8、根据spuId查询spu详情海报：pms_spu_desc
        //依赖于1的结果
        CompletableFuture<Void> c8 = c1.thenAcceptAsync((skuEntity) -> {
            ResponseVo<SpuDescEntity> spuDescEntityResponseVo = pmsClient
                    .querySpuDescById(skuEntity.getSpuId());
            SpuDescEntity spuDescEntity = spuDescEntityResponseVo.getData();
            if (spuDescEntity != null) {
                itemVo.setSpuImages(Arrays.asList(StringUtils.split(spuDescEntity.getDecript()
                        , ",")));
            }
        }, executor);

//                ============================================
//        9、根据spuId查询它所有的sku的 (销售属性和值集合) 的集合:
        //依赖于1的结果
        CompletableFuture<Void> c9 = c1.thenAcceptAsync((skuEntity) -> {
//        pms_sku:根据spuId查询自己的skuId集合
//        pms_attr:联查判断attr是不是销售属性
//        pms_sku_attr_value:根据上面的skuId集合查询 所有的销售属性对象（skuAttrValueEntity）
//        合并属性相同的对象  将值存到一个集合中
            //List<ItemSkuAttrsVo>
            //[ {attrId: 3 ,arrtName:"颜色" ,attrValues:["白色","黑色"]} ,{} ]
            ResponseVo<List<ItemSkuAttrsVo>> itemSkuAttrsVoResponseVo = pmsClient
                    .queryItemSkuAttrsVoBySpuId(skuEntity.getSpuId().toString());
            List<ItemSkuAttrsVo> itemSkuAttrsVos = itemSkuAttrsVoResponseVo.getData();
            if (!CollectionUtils.isEmpty(itemSkuAttrsVos)) {
                itemVo.setSkuAttrs(itemSkuAttrsVos);
            }
        }, executor);

//        10、根据skuId查询它所有的销售属性值 和attrId的映射的集合：默认选中
//        pms_sku_attr_value
        //{3 :"黑色", 4:"8G" , 5:"128G"}
        //和1并行
        CompletableFuture<Void> c10 = CompletableFuture.runAsync(() -> {
            ResponseVo<Map<Long, String>> mapResponseVo = pmsClient.querySkuSaleAttr(skuId);
            Map<Long, String> skuSaleAttrMap = mapResponseVo.getData();
            if (!CollectionUtils.isEmpty(skuSaleAttrMap)) {
                itemVo.setSkuAttrValue(skuSaleAttrMap);
            }
        }, executor);

//        11、根据spuId查询它所有的sku，每个sku的销售属性值拼接的字符串 和 此skuId映射：
        //依赖于1的结果
        CompletableFuture<Void> c11 = c1.thenAcceptAsync((skuEntity) -> {
//        pms_sku_attr_value
            ResponseVo<String> skusSaleAttrsJsonResponseVo = pmsClient
                    .querySkusSaleAttrsJson(skuEntity.getSpuId().toString());
            String skusSaleAttrsJson = skusSaleAttrsJsonResponseVo.getData();
            if (!StringUtils.isEmpty(skusSaleAttrsJson)) {
                itemVo.setSkusAttrValuesJson(skusSaleAttrsJson);
            }
        }, executor);

//        12、根据category3id查询属性分组、根据spuId查询spu所有的属性和值、根据skuId查询sku的所有的属性和值：
        //依赖于1的结果
        CompletableFuture<Void> c12 = c1.thenAcceptAsync((skuEntity) -> {
            //查询属性分组 和分组下的所有的属性(spu sku 的 attr_value)
            ResponseVo<List<ItemGroupVo>> groupAndAttrValuesResponseVo = pmsClient
                    .queryGroupAndAttrValues(skuEntity.getCategoryId().toString(),
                            skuEntity.getSpuId().toString(), skuId);
            List<ItemGroupVo> itemGroupVos = groupAndAttrValuesResponseVo.getData();
            if (!CollectionUtils.isEmpty(itemGroupVos)) {
                //排除空的组数据
                itemGroupVos = itemGroupVos.stream().filter(itemGroupVo ->
                        !CollectionUtils.isEmpty(itemGroupVo.getAttrs())).collect(Collectors.toList());
                itemVo.setGroups(itemGroupVos);
            }
        }, executor);

        try {
            CompletableFuture.allOf(c1,c2,c3,c4,c5,c6,c7,c8,c9,c10,c11,c12).get();
            //生成skuId的静态化页面：
//            createHtml(itemVo);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

        return itemVo;
    }
    // thymeleaf: 引入了场景启动器后 默认回向容器中注入 TemplateEngine
    @Autowired
    TemplateEngine engine;
    private void createHtml(ItemVo itemVo){
        executor.execute(()->{
            try {
                Context context = new Context();
                context.setVariable("itemVo",itemVo);
                //需要使用skuId作为页面的名称，skuId唯一  每次查询sku的详情页时 一定会传入skuId参数
                PrintWriter writer = new PrintWriter("F:\\"+itemVo.getSkuId()+".html");
                //参数1: 生成静态化页面的 html模板页面(item.html)    引擎会使用thymeleaf的前缀后缀拼接找页面
                //参数2：上下文对象，用来给模板页面共享数据(类似Model)
                engine.process("item",context , writer);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        });

    }
}
